package com.example.videocompressiondemo;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.iceteck.silicompressorr.SiliCompressor;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    Button button, button1, button3;
    ImageView button2;
    StandardGSYVideoPlayer videoPlayer;

    OrientationUtils orientationUtils;

    List<Uri> list = new ArrayList<>();

    RecyclerView recyclerView;
    int SELECT_TYPE;

    BaseQuickAdapter<File, BaseViewHolder> adapter;

    List<File> files = new ArrayList<>();
    List<File> fileList = new ArrayList<>();

    @SuppressLint("CheckResult")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        RxPermissions rxPermissions = new RxPermissions(MainActivity.this);
        rxPermissions.requestEachCombined(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {

                    }
                });

    }

    private void initView() {
        button = findViewById(R.id.button);
        videoPlayer = findViewById(R.id.img);
        button.setOnClickListener(this);
        button1 = findViewById(R.id.button1);
        button1.setOnClickListener(this);
        button2 = findViewById(R.id.button2);
        button3=findViewById(R.id.btn);
        button3.setOnClickListener(this);
        recyclerView = findViewById(R.id.recyclerview);

        CustomGridLayoutManager customGridLayoutManager = new CustomGridLayoutManager(this);
        customGridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        customGridLayoutManager.setScrollEnabled(false);

        recyclerView.setLayoutManager(customGridLayoutManager);

        //增加title
        videoPlayer.getTitleTextView().setVisibility(View.VISIBLE);
        //设置返回键
        videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        //设置旋转
        orientationUtils = new OrientationUtils(this, videoPlayer);
        //设置全屏按键功能,这是使用的是选择屏幕，而不是全屏
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                orientationUtils.resolveByClick();
            }
        });
        //是否可以滑动调整
        videoPlayer.setIsTouchWiget(true);
        //设置返回按键功能
        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        videoPlayer.startPlayLogic();
    }

    private void selectVido() {
        Matisse.from(MainActivity.this)
                .choose(MimeType.ofVideo())
                .captureStrategy(new CaptureStrategy(true, "com.example.videocompressiondemo.fileprovider")) //是否拍照功能，并设置拍照后图片的保存路径
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(1);
    }

    private void selectImg() {
        Matisse.from(MainActivity.this)
                .choose(MimeType.ofImage())
                .countable(true)
                .captureStrategy(new CaptureStrategy(true, "com.example.videocompressiondemo.fileprovider")) //是否拍照功能，并设置拍照后图片的保存路径
                .maxSelectable(1)
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.85f)
                .imageEngine(new Glide4Engine())
                .forResult(1);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {


            if (SELECT_TYPE == 1) {//视频压缩
                Observable.create(new ObservableOnSubscribe<File>() {
                    @Override
                    public void subscribe(ObservableEmitter<File> emitter) throws Exception {
//                        File fileByUri = FileUtil.getFileByUri(Matisse.obtainPathResult(data).get(0), MainActivity.this);

                        String path = SiliCompressor.with(MainActivity.this).compressVideo(Matisse.obtainPathResult(data).get(0), getExternalFilesDir(Environment.DIRECTORY_MOVIES).getPath());
                        emitter.onNext(new File(path));
                    }
                }).subscribeOn(Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<File>() {
                            @Override
                            public void accept(File file) throws Exception {
                                if (file != null) {
                                    videoPlayer.setUp(file.toURL().toString(), false, "测试");
                                } else {
                                    Toast.makeText(MainActivity.this, "视频压缩出现问题", Toast.LENGTH_SHORT).show();
                                }
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                Log.e("视频压缩出现问题", throwable.getMessage());
                            }
                        });
            } else {


                files.clear();
                for (int i = 0; i < Matisse.obtainResult(data).size(); i++) {
                    File file = FileUtil.getFileByUri(Matisse.obtainResult(data).get(i), MainActivity.this);
                    files.add(file);
                }

                compression();
            }

        }
    }

    private void initAdapter() {
        LogUtils.e("initAdapter初始化了");

        adapter = new BaseQuickAdapter<File, BaseViewHolder>(R.layout.item, fileList) {
            @Override
            protected void convert(BaseViewHolder helper, File item) {

                Glide.with(MainActivity.this).load(item).into((ImageView) helper.getView(R.id.item_img));
            }
        };

        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                selectVido();
                SELECT_TYPE = 1;
                break;
            case R.id.button1:
                selectImg();
                SELECT_TYPE = 2;
            case R.id.button2:

                break;
            case R.id.btn:
                selectImg();
                SELECT_TYPE = 2;
                break;
        }
    }

    private void compression() {
        final int size = files.size();

        Luban.with(MainActivity.this)
                .load(files)
                .ignoreBy(100)
                .filter(new CompressionPredicate() {
                    @Override
                    public boolean apply(String path) {
                        return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                    }
                })
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {

                        fileList.add(file);

                        if (size == files.size()) {
                            LogUtils.e("大小一样");

                            if (adapter != null) {
                                LogUtils.e("通知适配器");
                                adapter.notifyDataSetChanged();
                            } else {
                                LogUtils.e("适配器初始化");
                                initAdapter();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                        Log.e("error", e.getMessage());

                    }
                }).launch();

    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoPlayer.onVideoResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        if (orientationUtils != null)
            orientationUtils.releaseListener();
    }

    @Override
    public void onBackPressed() {
        //先返回正常状态
        if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            videoPlayer.getFullscreenButton().performClick();
            return;
        }
        //释放所有
        videoPlayer.setVideoAllCallBack(null);
        super.onBackPressed();
    }
}
